import { ElMessage } from 'element-plus';
import html2canvas from 'html2canvas';
import { ANY_OBJECT } from '@/types/generic';

export const handlePrint = async (printElement: HTMLElement, title: string) => {
  if (!printElement) {
    ElMessage.warning('打印内容未准备好');
    return;
  }

  try {
    ElMessage.info('正在准备打印...');

    // 移除不需要的元素
    const elementsToRemove = printElement.querySelectorAll('.active-widget-drag, .menu');
    elementsToRemove.forEach(el => ((el as HTMLElement).style.display = 'none'));
    printElement = printElement.querySelector('.el-scrollbar__view') || printElement;
    // 转换为图片
    const canvas = await html2canvas(printElement, {
      logging: false,
      allowTaint: true,
      scale: 2,
      scrollY: 0,
      scrollX: 0,
      useCORS: true,
      backgroundColor: '#ffffff',
      onclone: documentClone => {
        // 在克隆的文档中添加打印样式
        const style = documentClone.createElement('style');
        style.textContent = `
          * {
            -webkit-print-color-adjust: exact !important;
            color-adjust: exact !important;
            print-color-adjust: exact !important;
          }
          table, th, tr, td {
            border: 1px solid #000 !important;
            border-collapse: collapse !important;
          }
          .el-table {
            border: 1px solid #000 !important;
          }
          .el-table__header-wrapper th {
            background-color: #ffffff !important;
            color: #000 !important;
            border: 1px solid #000 !important;
          }
          .el-table__body-wrapper td {
            border: 1px solid #000 !important;
          }
          /** element 样式重写，可参考这里 */
          .el-textarea__inner, .el-input__wrapper, .el-select__wrapper {
            box-shadow: none !important;
            border: 1px solid #dcdfe6 !important;
            border-radius: 4px !important;
            transition: none !important;
          }
          .no-print {
            display: none !important;
          }
        `;
        documentClone.head.appendChild(style);
      },
    });

    // 创建打印窗口
    const printWindow = window.open('', '_blank');
    if (!printWindow) {
      throw new Error('无法打开打印窗口');
    }

    // 写入打印内容
    printWindow.document.write(`
      <!DOCTYPE html>
      <html>
        <head>
          <title>${title}</title>
          <meta charset="utf-8">
          <style>
            @page {
              size: A4;
              margin: 0;
              margin-top: 0mm;
              margin-bottom: 0mm;
            }
            body {
              margin: 0;
              padding: 0;
              -webkit-print-color-adjust: exact !important;
              print-color-adjust: exact !important;
            }
            .container {
              padding: 28px;
              box-sizing: border-box;
            }
            img {
              max-width: 100%;
              height: auto;
              display: block;
              margin: 0 auto;
              page-break-inside: avoid;
            }
          </style>
        </head>
        <body>
          <div class="container">
            <img src="${canvas.toDataURL('image/png', 1.0)}" />
          </div>
          <script>
            window.onload = () => {
              setTimeout(() => {
                window.print();
                window.close();
              }, 500);
            };
          </script>
        </body>
      </html>
    `);
    printWindow.document.close();
    ElMessage.success('打印准备完成');
  } catch (error) {
    ElMessage.error('打印失败: ' + error);
    console.error('打印错误:', error);
  }
};
